<!--
 * @Description:
 * @Author: FangYaoTang
 * @Date: 2023-08-16 09:18:16
 * @LastEditor: FangYaoTang
 * @LastEditTime: 2023-08-16 09:18:17
 * @Copyright: by 南京桓羽信息科技有限公司 禁止任何形式（包含二次开发）转售系统源码，违者必究。
-->

<template>
  <view class="page_content">
    <view class="head_content">
      <CustomNavbar title="Account registration"></CustomNavbar>
    </view>
    <view class="main_content">
      <!-- <view class="logo">
				<image class="image" :src="config.system.company" mode="widthFix"></image>
			</view> -->
      <view class="input_box">
        <u-form ref="uForm" :model="form" :rules="rules">
          <u-form-item prop="name">
            <view class="input">
              <u-input
                v-model="form.name"
                clearable
                placeholderClass="placeholderClass"
                placeholder="Please enter user name"
              ></u-input>
            </view>
          </u-form-item>
          <u-form-item prop="phone">
            <view class="input phone">
              <!-- <country-code-selector :countryCode.sync="country"></country-code-selector> -->
              <u-input
                v-model="form.phone"
                placeholderClass="placeholderClass"
                clearable
                placeholder="Please input your Email"
              ></u-input>
            </view>
          </u-form-item>
          <u-form-item prop="code">
            <view class="input">
              <u-input
                v-model="form.code"
                placeholderClass="placeholderClass"
                clearable
                placeholder="Please enter SMS code"
              >
                <template slot="suffix">
                  <u-code
                    ref="uCode"
                    uniqueKey="register-code"
                    :keepRunning="true"
                    @change="codeChange"
                    :start-text="login.codeTips"
                    seconds="60"
                    end-text="Reacquire"
                    change-text="After xs"
                  ></u-code>
                  <view class="codebtn" @click="getCode">{{ login.codeTips }}</view>
                </template>
              </u-input>
            </view>
          </u-form-item>
          <u-form-item prop="invitCode">
            <view class="input">
              <u-input
                v-model="form.invitCode"
                placeholderClass="placeholderClass"
                clearable
                placeholder="Please enter the invitation code"
              ></u-input>
            </view>
          </u-form-item>
          <!-- <u-form-item prop="againPassword">
						<view class="input">
							<u-input v-model="form.againPassword" type="password" clearable placeholder="请再次输入密码"></u-input>
						</view>
					</u-form-item> -->
        </u-form>
      </view>
      <view class="button_box">
        <u-button text="register" :loading="buttonLoading" @click="submitHandle" />
      </view>
      <!-- <view class="check_box">
				<u-checkbox-group @change="labelChange">
					<u-checkbox :name="true" label="阅读并同意" labelSize="28rpx" labelColor="#333"></u-checkbox>
				</u-checkbox-group>
				<text class="text">《服务协议》</text>
				<text>和</text>
				<text class="text">《隐私协议》</text>
			</view> -->
      <view class="text_info">
        <text class="text" @click="goToLogin">Already have an account? Go to login</text>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
import countryCodeSelector from '../../components/vue-country-code-selector/index.vue'
let _options = null
export default {
  components: { countryCodeSelector },
  data() {
    return {
      country: 1,
      buttonStyle: {
        width: '100%',
        height: '100rpx',
        border: 'none',
        fontSize: '28rpx',
        color: '#fff',
        background: 'linear-gradient(90deg, #2A82E4, #D269FF)',
        borderRadius: '20rpx',
        margin: '0',
        fontWeight: 'bold'
      },
      buttonLoading: false,
      login: {
        codeTips: 'Get SMS code', // 验证码提示文字
        checked: false, // 协议勾选
        platform: this.$utils.platforms() // 平台(H5 / wxMiniProgram / wxOfficialAccount)
      },
      form: {
        mobile: '', // 手机号
        code: '', // 验证码
        registerPassword: '', // 密码
        againPassword: '', // 确认密码
        invitCode: ''
      },
      rules: {
        phone: [
          { required: true, message: 'Please input your Email！', trigger: ['blur', 'change'] },
          {
            validator: this.$utils.checkEmail,
            trigger: ['change', 'blur']
          }
        ],
        code: [
          {
            required: true,
            message: 'please enter verification code！',
            trigger: ['blur', 'change']
          }
          // {
          //   min: 4,
          //   max: 6,
          //   message: 'Please enter the 4~6 digit verification code',
          //   trigger: ['blur', 'change']
          // }
        ],
        // code: [
        //   { required: true, message: 'Please enter password', trigger: ['blur', 'change'] },
        // { validator: this.$utils.checkPassword, trigger: ['change', 'blur'] }
        // ],
        registerPassword: [
          {
            required: true,
            message: 'Please enter a combination of letters + numbers for your password',
            trigger: ['blur', 'change']
          },
          { min: 6, max: 20, message: 'Password format is wrong', trigger: ['blur', 'change'] },
          { validator: this.$utils.checkPassword, trigger: ['change', 'blur'] }
        ],
        againPassword: [
          { required: true, message: 'Please enter password again', trigger: ['blur', 'change'] },
          {
            validator: (rule, value, callback) => {
              this.$utils.checkAgainPassword(rule, value, callback, this.form.registerPassword)
            },
            trigger: ['change', 'blur']
          }
        ],
        name: [{ required: true, message: 'Please enter user name', trigger: ['blur', 'change'] }]
        // invitCode:[
        //   {required: true, message: '请输入邀请码', trigger: ['blur', 'change']}
        // ]
      }
    }
  },
  computed: { ...mapGetters('app', ['config', 'share']) },
  onLoad(options) {
    _options = options || {}
    if (options && options.id) {
      this.form.invitCode = options.id
    }
  },
  onReady() {
    this.$nextTick(() => {
      this.$refs.uForm.setRules(this.rules)
    })
  },
  methods: {
    ...mapActions('user', ['getUserInfo']),
    submitHandle() {
      // if(!this.login.checked) {
      // 	this.$u.toast('请勾选并同意协议')
      // 	return
      // }
      this.$refs.uForm
        .validate()
        .then((res) => {
          const obj = {
            phone: this.form.phone,
            code: this.form.code,
            // password: this.form.code,
            platform: this.login.platform,
            spm: this.share.spm || '',
            invitCode: this.form.invitCode,
            name: this.form.name
            // email: this.form.phone
          }
          this.registerAccount(obj)
        })
        .catch((err) => {
          console.log(err, '验证未通过')
        })
    },
    // 1.注册账号
    registerAccount(obj) {
      this.$request('login.register', obj).then((res) => {
        this.$u.toast('registration success')
        this.getUserInfo(res.data.token)
        this.redirectPath()
        // uni.switchTab({ url: '/pages/home/user' })
      })
    },
    goToLogin() {
      uni.redirectTo({url:'/pages/login/login'})
    },
    // 重定向页面
    redirectPath(type) {
      if (type == 'wxoa') {
        // #ifdef H5
        const lastPage = uni.getStorageSync('lastPage')
        if (lastPage && lastPage.indexOf('/pages/login/login') == -1) {
          uni.removeStorageSync('lastPage')
          uni.switchTab({
            url: lastPage,
            success: () => {},
            fail: () => {
              uni.switchTab({
                url: '/pages/home/index',
                success: () => {
                  uni.navigateTo({ url: lastPage })
                }
              })
            }
          })
        } else {
          uni.switchTab({ url: '/pages/home/user' })
        }
        // #endif
      } else {
        var pages = getCurrentPages() // 获取页面指针数组
        if (pages.length > 1) {
          let lastPage = {}
          for (let i = pages.length - 2; i >= 0; i--) {
            if (pages[i].route != 'pages/login/index' && !lastPage.route) {
              lastPage = pages[i]
            }
          }

          // if (pages[pages.length - 2].route != 'pages/login/index') {
          //   lastPage = pages[pages.length - 2]
          // }
          // if (pages[pages.length - 3].route != 'pages/login/index') {
          //   lastPage = pages[pages.length - 3]
          // }
          // var lastPage = pages[pages.length - 2] // 获取当前页
          let paramsArr = []
          for (let key in lastPage.options) {
            paramsArr.push(key + '=' + lastPage.options[key])
          }
          try {
            this.$utils.navigateTo(
              {
                url: '/' + lastPage.route + '?' + paramsArr.join('&')
              },
              1
            )
          } catch (error) {
            wx.switchTab({
              url: '/pages/home/index'
            })
          }
        } else {
          wx.switchTab({
            url: '/pages/home/index'
          })
        }
      }
    },
    labelChange(detail) {
      this.login.checked = detail[0] ? detail[0] : false
    },
    codeChange(text) {
      this.login.codeTips = text
    },
    getCode() {
      if (!this.form.phone) {
        this.$u.toast('Please input your Email！')
        return
      }
      let obj = {
        phone: this.form.phone,
        event: 'register'
      }
      if (this.$refs.uCode.canGetCode) {
        uni.showLoading({ title: 'Getting verification code！' })
        this.$request('login.sendCode', obj, false)
          .then((res) => {
            uni.hideLoading()
            uni.$u.toast('Verification code sent！')
            this.$refs.uCode.start()
          })
          .catch((err) => {
            uni.hideLoading()
            uni.$u.toast('Failed to send verification code！')
          })
      } else {
        uni.$u.toast('Send after countdown ends！')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/.u-input__content__field-wrapper__field {
  font-size: 24rpx !important;
}
.input {
  background-color: rgb(33, 33, 33) !important;
}

.page_content {
  background-image: url('../../static/images/login-background.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  min-height: 100vh;
}

.main_content {
  padding: 50rpx;
  overflow-y: auto;

  .logo {
    width: 100%;
    padding: 40rpx 100rpx 100rpx 100rpx;

    .image {
      width: 100%;
    }
  }

  .input_box {
    margin-top: 250rpx;

    ::v-deep .u-form {
      // .u-form-item__body {
      // 	padding: 0 0 40rpx 0 !important;
      // }

      .u-form-item__body__right__message {
        margin-left: 0 !important;
        line-height: 1.5em;
        font-size: 28rpx;
        padding: 0 10rpx 20rpx 10rpx;
      }
    }

    /deep/.u-form-item {
      border-bottom: none;
    }

    .input.phone {
      color: #fff;
      display: flex;
      align-items: center;
    }

    .input {
      width: 100%;

      ::v-deep .u-input {
        height: 100rpx;
        // background: #F7F8F9;
        border-radius: 0;
        border: none;
        padding: 12rpx 24rpx !important;
        // border-bottom: 1px solid rgba(255, 255, 255,0.1) !important;
      }

      .codebtn {
        // font-size: 28rpx;
        // color: #333;
        padding-left: 15rpx;
        padding-right: 15rpx;
        height: 56rpx;
        border-radius: 28rpx;
        border: none;
        font-size: 30rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        color: $color-rgba-primary;
        display: flex;
        align-items: center;
        justify-content: center;
        color: $color-primary;
      }
    }
  }

  .button_box {
    margin: 120rpx 0 0;

    /deep/.u-button {
      width: 100%;
      height: 98rpx;
      border-radius: 23rpx;
      background: $color-primary;
      color: #ffffff;
      border-color: transparent !important;
      font-size: 34rpx;
      font-family: PingFangSC, PingFang SC;
    }
  }

  .check_box {
    display: flex;
    align-items: center;
    font-size: 28rpx;

    .text {
      color: #583ef2;
    }
  }

  .text_info {
    margin-top: 60rpx;
    text-align: center;

    .text {
      color: #626262;
      font-size: 28rpx;
    }
  }
}
</style>
